package com.finals.function.service;

import java.util.List;

import android.accessibilityservice.AccessibilityService;
import android.accessibilityservice.AccessibilityServiceInfo;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.text.TextUtils;
import android.util.Log;
import android.view.accessibility.AccessibilityEvent;

import com.finals.function.app.BaseApplication;
import com.finals.function.util.Util;

public class NotificationAccessibilityService extends AccessibilityService {

	BaseApplication mApp;

	@Override
	public void onCreate() {
		super.onCreate();
		mApp = (BaseApplication) getApplication();
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		return super.onStartCommand(intent, flags, startId);
	}

	@Override
	protected void onServiceConnected() {
		super.onServiceConnected();
		Log.i(Util.TAG, "服务连接上了");
		mApp.setAccessibilityService(this);
		InitInfo();
	}

	private void InitInfo() {
		AccessibilityServiceInfo serviceInfo = new AccessibilityServiceInfo();
		serviceInfo.eventTypes = AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED;
		serviceInfo.feedbackType = AccessibilityServiceInfo.FEEDBACK_HAPTIC;
		serviceInfo.flags = AccessibilityServiceInfo.DEFAULT;
		serviceInfo.notificationTimeout = 100;
		setServiceInfo(serviceInfo);
	}

	String currentPackage;

	@Override
	public void onAccessibilityEvent(AccessibilityEvent event) {
		int currentType = event.getEventType();
		switch (currentType) {
		case AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED:
			currentPackage = event.getPackageName().toString();
			break;
		default:
			break;
		}
	}

	@Override
	public void onInterrupt() {
		Log.i(Util.TAG, "中断服务");
	}

	@Override
	public boolean onUnbind(Intent intent) {
		Log.i(Util.TAG, "解绑服务");
		return true;
	}

	@Override
	public void onDestroy() {
		mApp.setAccessibilityService(null);
		super.onDestroy();
	}

	public void OpenRecent() {
		PackageManager manager = getPackageManager();

		if (!TextUtils.isEmpty(currentPackage)) {
			Intent intent = new Intent(Intent.ACTION_MAIN);
			intent.setPackage(currentPackage);
			List<ResolveInfo> result = manager.queryIntentActivities(intent, 0);
			if (result == null || result.size() == 0) {
				Log.e("Finals", "没有获取到数据");
				return;
			}
			String className = result.get(0).activityInfo.name;
			ComponentName cn = new ComponentName(currentPackage, className);

			Intent newIntent = new Intent(Intent.ACTION_MAIN);
			newIntent.addCategory(Intent.CATEGORY_LAUNCHER);
			newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			newIntent.setComponent(cn);
			Log.e("Finals", "取到数据" + currentPackage + " " + className);
			try {
				mApp.startActivity(newIntent);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
